package com.pansoft.openplanet.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import androidx.core.app.ActivityCompat;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.efounder.chat.activity.ChatWebViewActivity;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.utils.ResStringUtil;
import com.pansoft.openplanet.R;
import com.pansoft.openplanet.manager.OpenPlanetLoginManager;
import com.pansoft.openplanet.util.LoginFlowManager;
import com.pansoft.openplanet.util.TCRequestUtil;
import com.utilcode.util.ToastUtils;

import org.json.JSONObject;

import java.util.HashMap;

/**
 * 创建安全账户的页面
 * Created by will on 18-3-24.
 *
 * @author will
 */

public class RegisterUserActivity extends TCBaseActivity implements View.OnClickListener, OpenPlanetLoginManager.LoginListener {

    private EditText etNickName;
    private EditText etPassword;
    private EditText etConfirmPassword;
    private CheckBox checkBox;
    private Button tvCreateWallet;
    private String number = "";
    private String planetName = "";
    private String inviteCode;

    private OpenPlanetLoginManager loginManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.talk_chain_activity_register);
        if (getIntent().getExtras() != null && getIntent().getExtras().get("number") != null) {
            number = (String) getIntent().getExtras().get("number");
            inviteCode = getIntent().getExtras().getString("inviteCode");
            planetName = getIntent().getExtras().getString("planet");
        }
        initView();
        loginManager = new OpenPlanetLoginManager(this);
        loginManager.setLoginListener(this);
    }

    private void initView() {
        ImageView ivBack = (ImageView) findViewById(R.id.iv_back);
        ivBack.setOnClickListener(this);
        TextView tvTitle = (TextView) findViewById(R.id.tv_title);
        tvTitle.setText(R.string.open_planet_create_safety_account);
        etConfirmPassword = (EditText) findViewById(R.id.et_confirm_password);
        etNickName = (EditText) findViewById(R.id.et_nick_name);
        etPassword = (EditText) findViewById(R.id.et_password);
        checkBox = (CheckBox) findViewById(R.id.checkBox);
        checkBox.setChecked(true);
        TextView tvTerms = (TextView) findViewById(R.id.tv_terms);
        tvTerms.setOnClickListener(this);
        tvCreateWallet = (Button) findViewById(R.id.tv_create_wallet);
        tvCreateWallet.setOnClickListener(this);

        etConfirmPassword.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                if (i == EditorInfo.IME_ACTION_SEND || i == EditorInfo.IME_ACTION_DONE
                        || i == EditorInfo.IME_ACTION_GO || i == EditorInfo.IME_ACTION_NEXT
                        || i == EditorInfo.IME_ACTION_NONE || i == EditorInfo.IME_NULL) {
                    if (etPassword.getText().toString().trim().length() < 8) {
                        ToastUtils.showShort(R.string.open_planet_password_number);

                    } else if (!etPassword.getText().toString().equals(etConfirmPassword.getText().toString())) {
                        showPassErrorAlertdialog();
                    }
                }
                return false;
            }
        });
    }

    private void showPassErrorAlertdialog() {
        new AlertDialog.Builder(RegisterUserActivity.this)
                .setTitle(R.string.common_text_hint)
                .setMessage(R.string.common_text_pw_repeat_input_not_same)
                .setPositiveButton(R.string.common_text_confirm, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        etPassword.setText("");
                        etConfirmPassword.setText("");
                        etPassword.setFocusable(true);
                        etPassword.setFocusableInTouchMode(true);
                        etPassword.requestFocus();
//                                        CreateWalletActivity.this.getWindow().setSoftInputMode
//                                                (WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
                        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                    }
                })
                .create().show();
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.iv_back) {
            finish();
        } else if (id == R.id.tv_terms) {
//            Intent intent = new Intent(this, TermsActivity.class);
//            startActivity(intent);
            //跳转隐私条款页面
            //String url = "https://mobile.solarsource.cn/ospstore/TurboPay/Privacy-en.html";
//            if (MultiLanguageUtil.getInstance().getSetLanguageLocale().getLanguage().equals(Locale.CHINA.getLanguage())) {
//                url = "https://mobile.solarsource.cn/ospstore/TurboPay/Privacy-zh-Hans.html";
//            }
            String url = ResStringUtil.getString(R.string.open_planet_term_service);
            Intent intent = new Intent(RegisterUserActivity.this, ChatWebViewActivity.class);
            intent.putExtra("url", url);
            startActivity(intent);

        } else if (id == R.id.tv_create_wallet) {
            String pass = etPassword.getText().toString().trim();
            String confirmPass = etConfirmPassword.getText().toString().trim();

            if (pass.length() < 8) {
                ToastUtils.setGravity(Gravity.CENTER, 0, 0);
                ToastUtils.showShort(R.string.open_planet_password_number);
                return;
            }
            if (pass.equals("") || confirmPass.equals("") || !pass.equals(confirmPass)) {

                showPassErrorAlertdialog();
                return;
            }

            registerUser();
        }
    }

    private void registerUser() {
        if (checkBox.isChecked()) {
            if (etNickName.getText().toString().equals("") || etPassword.getText().toString().equals("") ||
                    etConfirmPassword.getText().toString().equals("") ||
                    !etConfirmPassword.getText().toString().equals(etPassword.getText().toString())) {
                ToastUtils.showShort(R.string.common_text_input_name_and_pw);
            } else {

                //点击注册按钮 先判断用户是否存在（避免注册过再次点击注册出现的问题）
                showLoading(R.string.talk_chain_loding_wait);
                HashMap<String, String> params1 = new HashMap<>();
                params1.put("phoneNumber", number);
                TCRequestUtil.getCommonRequest(TAG, "user/login", params1, new TCRequestUtil.TCRequestCallback() {
                    @Override
                    public void onSuccess(String response) {
                        dismissLoading();
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            if (jsonObject.getString("result").equals("success")) {

                                //未注册，短信验证码登录
                                if (jsonObject.optString("userStatus", "").equals("0")) {
                                    startRegister();
                                    //已注册，跳创建钱包登录
                                } else if (jsonObject.optString("userStatus", "").equals("1")) {
                                    Intent intent = new Intent(RegisterUserActivity.this, CreateWalletActivity.class);
                                    //intent.putExtra("userName", etNickName.getText().toString());
                                    // intent.putExtra("password", etPassword.getText().toString());
                                    intent.putExtra("number", number);
                                    intent.putExtra("loginPwd", etPassword.getText().toString());
                                    EnvironmentVariable.setProperty("old_user", "0");
                                    startActivity(intent);
                                    ActivityCompat.finishAffinity(RegisterUserActivity.this);
                                    //finish();
                                } else if (jsonObject.optString("userStatus", "").equals("-1")) {
                                    //未注册，跳过邀请码，直接验证短信码
                                    startRegister();
                                }
                            } else {
                                showFailAlert(ResStringUtil.getString(R.string.common_text_http_request_fail));
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            dismissLoading();
                            showFailAlert(ResStringUtil.getString(R.string.common_text_http_request_fail));
                        }
                    }

                    @Override
                    public void onFail(String error) {
                        dismissLoading();
                        showFailAlert(ResStringUtil.getString(R.string.common_text_http_request_fail));
                    }
                });

                //判断用户end
            }
        } else {
            dismissLoading();
            ToastUtils.showShort(R.string.open_planet_create_account_terms);
        }
    }

    private void startRegister() {

        showLoading(R.string.open_planet_iscreateing);
        HashMap<String, String> params = new HashMap<>();
        params.put("phoneNumber", number);
        params.put("inviteCode", inviteCode==null?"":inviteCode);
        params.put("planet", planetName);
        params.put("userName", etNickName.getText().toString());
        params.put("password", etPassword.getText().toString());
        TCRequestUtil.getCommonRequest(TAG, "user/register", params, new TCRequestUtil.TCRequestCallback() {
            @Override
            public void onSuccess(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.getString("result").equals("success")) {

                        // 注册成功 当前是注册状态（走完创建钱包 导入通讯录等操作 注册状态才能结束）
                        EnvironmentVariable.setProperty(LoginFlowManager.getIsRegisterKey(number), "true");
                        //创建用户成功后 取登录
                        login();
                    } else {
                        dismissLoading();
//                                progressDialog.dismiss();
                        if (jsonObject.has("msg")) {
                            showFailAlert(jsonObject.getString("msg"));
                        } else {
                            showFailAlert(ResStringUtil.getString(R.string.open_planet_create_user_fail));
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    //progressDialog.dismiss();
                    dismissLoading();
                    showFailAlert(ResStringUtil.getString(R.string.open_planet_create_user_fail));
                }
            }

            @Override
            public void onFail(String error) {
                dismissLoading();
                showFailAlert(ResStringUtil.getString(R.string.open_planet_create_user_fail));
            }
        });
    }

    private void login() {
        loginManager.login(number, etPassword.getText().toString(), "password");
    }

    private void showFailAlert(String message) {
        if (isFinishing() || isDestroyed()) {
            return;
        }
        new AlertDialog.Builder(RegisterUserActivity.this)
                .setTitle(R.string.common_text_hint)
                .setMessage(message)
                .setPositiveButton(R.string.common_text_confirm, null)
                .create().show();

    }

    @Override
    public void tcLoginSuccess() {
        Intent intent = new Intent(RegisterUserActivity.this, CreateWalletActivity.class);
        intent.putExtra("userName", etNickName.getText().toString());
        intent.putExtra("password", etPassword.getText().toString());
        intent.putExtra("number", number);
        intent.putExtra("loginPwd", etPassword.getText().toString());
        startActivity(intent);
        ActivityCompat.finishAffinity(RegisterUserActivity.this);
    }

    @Override
    public void showLoginLoading(String msg) {
        showLoading(msg);
    }

    @Override
    public void dismissLoginloading() {
        dismissLoading();
    }

    @Override
    public void tcLoginFail(String error) {
        showFailAlert(error);
    }
}
